package com.cjx.minio.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 *@Author cjunxian
 *@date 2020/10/29  11:24:40
 *@doc 异步配置线程池
 *@version 1.0.0
 */
@Configuration
public class AsyncThreadPoolConfig {

    /**
     * 线程池最大的大小
     */
    private static final int MAX_POOL_SIZE = 5;

    /**
     * 线程池的基本大小
     */
    private static final int CORE_POOL_SIZE = 5;

    /**
     * 配置队列大小
     */
    private static final int QUEUE_CAPACITY_SIZE = 50;

    /**
     * 配置线程活跃时间
     */
    private static final int KEEP_ALIVE_SECONDS = 200;

    /**
     * 配置线程池中的线程的名称前缀
     */
    private static final String THREAD_NAME_PREFIX = "async-task-thread-pool-";

    /**
     * 不影响主线程，异步方法交给单独的线程完成
     * 这里设置线程池基本属性
     */
    @Bean("taskExecutor")
    public AsyncTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
        taskExecutor.setCorePoolSize(CORE_POOL_SIZE);
        taskExecutor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        taskExecutor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        taskExecutor.setQueueCapacity(QUEUE_CAPACITY_SIZE);
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }
}